package risk.control.application.activity;

import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.target.Target;

import java.util.HashMap;

import risk.control.application.R;
import risk.control.application.activity.base.BaseActivity;
import risk.control.application.http.Api;
import risk.control.application.http.callback.UiCallback;
import risk.control.application.utils.RouteJump;
import risk.control.application.utils.WindowSwingUtils;
import risk.control.application.utils.mmkv.MMKVUtils;
import risk.control.application.utils.mmkv.MMKV_KEY;

/**
 * 登录页
 */
public class LoginActivity extends BaseActivity {

    private TextView mTvTitle;
    private Button mBtnLogin;
    private EditText mEtUser;
    private EditText mEtPwd;
    private EditText mEtVerification;
    private ImageView mIvVerification;

    private String mCaptchaKey;

    @Override
    protected void postData(HashMap<String, String> dataMap) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        intiView();
        intiData();
        initListener();
    }


    private void intiView() {
        mTvTitle = findViewById(R.id.tv_login_title);
        mBtnLogin = findViewById(R.id.btn_login);
        mEtUser = findViewById(R.id.et_user);
        mEtPwd = findViewById(R.id.et_pwd);
        mEtVerification = findViewById(R.id.et_verification);
        mIvVerification = findViewById(R.id.iv_verification);
    }

    private void intiData() {
        mTvTitle.setText("欢迎使用");
        getVerificationCode();
        //获取最后一次登录成功的用户名
        String name = MMKVUtils.getString(MMKV_KEY.LAST_LOGIN_NAME);
        if (name != null && !name.isEmpty()) {
            mEtUser.setText(name);
        }
    }

    private void initListener() {
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();

            }
        });

        mIvVerification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVerificationCode();
            }
        });
    }

    //获取验证码
    private void getVerificationCode() {
        getNetWordData(Api.verificationCode, new HashMap<>(), new UiCallback() {
            @Override
            public void onSuccess(String respData) {
                JSONObject jsonObject = (JSONObject) JSON.parse(respData);
                JSONObject data = jsonObject.getJSONObject("data");
                String imgBase64 = data.getString("imgBase64");
                mCaptchaKey = data.getString("captchaKey");
                //显示图片
                byte[] decodedBytes = Base64.decode(imgBase64, Base64.DEFAULT);
                loadCodePic(decodedBytes);
            }

            @Override
            public void onSpecialCode(String errorData) {
                loadCodePic(null);//显示错误图
            }

            @Override
            public void onResolve() {
                loadCodePic(null);//显示错误图
            }
        });
    }

    //加载验证码码图片
    private void loadCodePic(byte[] decodedBytes) {
        Glide.with(LoginActivity.this)//
                .load(decodedBytes)//
                .error(R.mipmap.navigation_refresh) // 加载失败的占位图
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) // 使用原始尺寸
                .transition(DrawableTransitionOptions.withCrossFade()) // 添加淡入淡出效果
                .diskCacheStrategy(DiskCacheStrategy.NONE) // Base64图片通常不需要缓存
                .into(mIvVerification);
    }

    private void login() {
        String userStr = mEtUser.getText().toString();
        String pwdStr = mEtPwd.getText().toString();
        String verificationStr = mEtVerification.getText().toString();
        if (userStr.isEmpty()) {
            WindowSwingUtils.shake(mEtUser);
            return;
        }
        if (pwdStr.isEmpty()) {
            WindowSwingUtils.shake(mEtPwd);
            return;
        }
        if (verificationStr.isEmpty()) {
            WindowSwingUtils.shake(mEtVerification);
            return;
        }
        showLoadDialog("正在登录...");
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("captchaKey", mCaptchaKey);
        paramsMap.put("captcha", verificationStr);
        paramsMap.put("userName", userStr);
        paramsMap.put("pwd", pwdStr);
        paramsMap.put("loginType", "0");//密码登录
        //请求登录
        getNetWordData(Api.login, paramsMap, new UiCallback() {
            @Override
            public void onSuccess(String respData) {
                dismissLoadDialog();
                //保存登录成功的用户名
                MMKVUtils.putString(MMKV_KEY.LAST_LOGIN_NAME, userStr);
                //持久化用户信息
                MMKVUtils.putString(MMKV_KEY.KV_USER_INFO_DATA, respData);
                //跳转主页
                RouteJump.start(LoginActivity.this, RouteJump.MAIN_ACTION, null, true, true);
            }

            @Override
            public void onSpecialCode(String errorData) {
                dismissLoadDialog();
            }

            @Override
            public void onResolve() {
                dismissLoadDialog();
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}





